package com.yihu.wlyy.web.doctor.patient;

import java.text.DateFormat;
import java.util.*;

import com.fasterxml.jackson.annotation.JsonBackReference;
import com.yihu.wlyy.entity.*;
import com.yihu.wlyy.entity.doctor.Doctor;
import com.yihu.wlyy.entity.doctor.DoctorPatientGroup;
import com.yihu.wlyy.entity.doctor.DoctorPatientGroupInfo;
import com.yihu.wlyy.entity.patient.Patient;
import com.yihu.wlyy.repository.SignFamilyDao;
import org.apache.commons.lang3.StringUtils;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.yihu.wlyy.service.app.account.DoctorInfoService;
import com.yihu.wlyy.service.app.account.DoctorPatientGroupService;
import com.yihu.wlyy.service.app.account.PatientInfoService;
import com.yihu.wlyy.service.app.team.DrHealthTeamService;
import com.yihu.wlyy.util.CommonUtil;
import com.yihu.wlyy.util.DateUtil;
import com.yihu.wlyy.web.BaseController;

/**
 * 医生端：患者分组管理
 *
 * @author George
 */
@Controller
@RequestMapping(value = "/doctor/patient_group")
public class DoctorPatientGroupController extends BaseController {

    @Autowired
    private DoctorInfoService doctorInfoService;
    @Autowired
    private PatientInfoService patientInfoService;
    @Autowired
    private DrHealthTeamService drHealthTeamService;
    @Autowired
    private DoctorPatientGroupService doctorPatientGroupService;
    @Autowired
    private SignFamilyDao signFamilyDao;
    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Autowired
    private StringRedisTemplate redisTemplate;

    private final int DOCTOR_PATIENT_OBJECT_LENGTH = 13;

    /**
     * 医生管理的患者总数
     *
     * @return
     */
    @RequestMapping(value = "amount")
    @ResponseBody
    public String amount() {
        try {
            // 获取医生下的患者
            int amount = doctorInfoService.amountPatientByDoctorSign(getUID());
            return write(200, "获取患者总数成功！", "data", amount);
        } catch (Exception e) {
            error(e);
            return invalidUserException(e, -1, "获取患者总数失败！");
        }
    }

    /**
     * 我的患者查询接口
     *
     * @return
     */
    @RequestMapping(value = "patients")
    @ResponseBody
    public String patients() {
        try {
            System.out.println("patients_start:" + new Date());
            JSONArray array = new JSONArray();
            // 获取分组
            Iterable<DoctorPatientGroup> grouplists = doctorInfoService.findDoctorPatientGroup(getUID());
            // 获取医生下的患者
            List<Object> doctorPatients = doctorInfoService.findPatientByDoctorSign(getUID());

            if (doctorPatients != null) {
                for (DoctorPatientGroup grouplist : grouplists) {
                    if (grouplist == null) {
                        continue;
                    }

                    JSONObject groupJson = new JSONObject();
                    Map<String, JSONObject> patientsMap = new HashMap<>();

                    for (Object temp : doctorPatients) {
                        Object[] object = (Object[]) temp;
                        if (object == null || object.length != DOCTOR_PATIENT_OBJECT_LENGTH) {
                            continue;
                        }
                        // 签约类型（1表示三师签约，2表示家庭签约）
                        Object signType = object[11];
                        // 分组标识
                        String group = (String) object[0];
                        // 患者标识
                        Object code = object[1];
                        // 姓名
                        Object name = object[2];
                        // 头像
                        Object photo = object[3];
                        // 生日
                        Date birthday = (Date) object[4];
                        // 性别
                        Object sex = object[5];
                        // 病情：0绿标，1黄标，2红标
                        Object diseaseCondition = object[6];
                        // 疾病类型，0健康，1高血压，2糖尿病，3高血压+糖尿病
                        Object disease = object[7];
                        // 病历数
                        Object recordAmount = object[8];
                        // 随手记数
                        Object partAmount = object[9];
                        // 签约日期
                        Date qyrq = (Date) object[10];
                        //患者身份证
                        Object idcard = object[12];
                        if (StringUtils.equals(group, grouplist.getCode())) {
                            if (patientsMap.containsKey(object[1].toString())) {
                                if ((patientsMap.get(object[1].toString()).get("signType").toString().equals("1") || patientsMap.get(object[1].toString()).get("signType").toString().equals("2")) &&
                                        patientsMap.get(object[1].toString()).get("signType").toString().equals(signType.toString())) {
                                    continue;
                                }
                                patientsMap.get(object[1].toString()).put("signType", 3);
                                continue;
                            }
                            JSONObject patientJson = new JSONObject();
                            // 设置患者标识
                            patientJson.put("code", code);
                            // 设置患者姓名
                            patientJson.put("name", name);
                            // 设置患者头像
                            patientJson.put("photo", photo);
                            // 设置患者年龄
                            patientJson.put("age", DateUtil.getAgeByBirthday(birthday));
                            // 设置患者性别
                            patientJson.put("sex", sex);
                            // 设置患者病情
                            patientJson.put("diseaseLevel", diseaseCondition);
                            // 设置患者病种
                            patientJson.put("disease", disease);
                            // 设置病历记录总数
                            patientJson.put("recordAmount", recordAmount);
                            // 设置病历片段总数
                            patientJson.put("partAmount", partAmount);
                            // 设置签约日期
                            patientJson.put("qyrq", DateUtil.dateToStr(qyrq, DateUtil.YYYY_MM_DD));
                            // 设置签约类型
                            patientJson.put("signType", signType);
                            patientJson.put("idcard", idcard);

                            String diseases = redisTemplate.opsForValue().get("disease:" + code.toString());
                            if(!StringUtils.isEmpty(diseases)){
                                patientJson.put("diseases",new JSONArray(diseases));
                            }else{
                                patientJson.put("diseases","");
                            }

                            patientsMap.put(code.toString(), patientJson);
                            //groupPatientArray.put(patientJson);
                        }
                    }

                    JSONArray groupPatientArray = new JSONArray(patientsMap.values());

                    // 设置分组标识
                    groupJson.put("code", grouplist.getCode());
                    // 设置分组名称
                    groupJson.put("name", grouplist.getName());
                    // 设置患者数
                    groupJson.put("total", groupPatientArray.length());
                    // 设置患者列表
                    groupJson.put("patients", groupPatientArray);
                    array.put(groupJson);
                }
            }
            System.out.println("patients_end:" + new Date());
            return write(200, "患者列表查询成功！", "data", array);
        } catch (Exception e) {
            error(e);
            return invalidUserException(e, -1, "患者列表查询失败！");
        }
    }

    /**
     * 查询患者按疾病分组
     *
     * @return
     */
    @RequestMapping(value = "/patients_disease")
    @ResponseBody
    public String patientsByDisease(String type, String patientName) {
        try {
            System.out.println("patients_disease_start:" +new Date());
            JSONArray array = new JSONArray();
            // 获取医生下的患者
            List<Object> doctorPatients = new ArrayList<>();
            Map<String, JSONObject> tnbGroup = new HashMap<>();
            Map<String, JSONObject> gxyGroup = new HashMap<>();
            Map<String, JSONObject> ptGroup = new HashMap<>();

            JSONObject ptGroupJson = new JSONObject();
            // 设置分组标识
            ptGroupJson.put("code", "0");
            // 设置分组名称
            ptGroupJson.put("name", "普通人群");
            // 设置患者数
            ptGroupJson.put("total", 0);

            JSONObject gxyGroupJson = new JSONObject();
            // 设置分组标识
            gxyGroupJson.put("code", "1");
            // 设置分组名称
            gxyGroupJson.put("name", "高血压人群");
            // 设置患者数
            gxyGroupJson.put("total", 0);

            JSONObject tnbGroupJson = new JSONObject();
            // 设置分组标识
            tnbGroupJson.put("code", "2");
            // 设置分组名称
            tnbGroupJson.put("name", "糖尿病人群");
            // 设置患者数
            tnbGroupJson.put("total", 0);


            if (StringUtils.isEmpty(patientName) && StringUtils.isEmpty(type)) {
                doctorPatients = doctorInfoService.getDoctorSignPatients(getUID());
            }
            if (StringUtils.isEmpty(patientName) && StringUtils.isNotEmpty(type)) {
                doctorPatients = doctorInfoService.getDoctorSignPatientsBySignType(getUID(), Integer.valueOf(type));
            }
            if (StringUtils.isNotEmpty(patientName) && StringUtils.isEmpty(type)) {
                doctorPatients = doctorInfoService.getDoctorSignPatientsLikeName(getUID(), patientName);
            }
            if (StringUtils.isNotEmpty(patientName) && StringUtils.isNotEmpty(type)) {
                doctorPatients = doctorInfoService.getDoctorSignPatientsByTypeName(getUID(), Integer.valueOf(type), patientName);
            }

            if (doctorPatients != null && doctorPatients.size() > 0) {
                for (Object temp : doctorPatients) {
                    Object[] object = (Object[]) temp;
                    String group = "0";
                    // 签约类型（1表示三师签约，2表示家庭签约）
                    Object signType = object[8];
                    // 患者标识
                    Object code = object[0];
                    // 姓名
                    Object name = object[1];
                    // 头像
                    Object photo = object[2];
                    // 生日
                    Date birthday = (Date) object[3];
                    // 性别
                    Object sex = object[4];
                    // 病情：0绿标，1黄标，2红标
                    Object diseaseCondition = object[5];
                    // 疾病类型，0健康，1高血压，2糖尿病，3高血压+糖尿病
                    Object disease = 0;
                    // 病历数
                    Object recordAmount = object[7];
                    // 签约日期
                    Date qyrq = (Date) object[9];
                    // 病历数
                    Object idcard = object[10];

                    String diseases = redisTemplate.opsForValue().get("disease:" + code.toString());

                    if(diseases != null){
                        JSONArray dis = new JSONArray(diseases);
                        boolean gxyFlag = false;
                        boolean tnbFlag = false;
                        for(int i = 0; i < dis.length();i ++){
                            JSONObject json = dis.getJSONObject(i);
                            if(json != null){
                                if(json.get("disease").toString().equals("1")){
                                    gxyFlag = true;
                                }
                                if(json.get("disease").toString().equals("2")){
                                    tnbFlag = true;
                                }
                            }
                        }
                        if(gxyFlag){
                            disease = 1;
                        }
                        if(tnbFlag){
                            disease = 2;
                        }
                        if(gxyFlag && tnbFlag){
                            disease = 3;
                        }
                    }
                    if (disease != null && StringUtils.isNotEmpty(disease.toString())) {
                        if (disease.toString().equals("1")) {
                            group = "1";
                        } else if (disease.toString().equals("2")) {
                            group = "2";
                        } else if (disease.toString().equals("3")) {
                            group = "3";
                        } else {
                            group = "0";
                        }
                    } else {
                        group = "0";
                    }

                    if (group.equals("0")) {
                        if (ptGroup.containsKey(object[0].toString())) {
                            if ((ptGroup.get(object[0].toString()).get("signType").toString().equals("1") || ptGroup.get(object[0].toString()).get("signType").toString().equals("2")) &&
                                    ptGroup.get(object[0].toString()).get("signType").toString().equals(signType.toString())) {
                                continue;
                            }
                            ptGroup.get(object[0].toString()).put("signType", 3);
                            continue;
                        }
                    } else if (group.equals("1")) {
                        if (gxyGroup.containsKey(object[0].toString())) {
                            if ((gxyGroup.get(object[0].toString()).get("signType").toString().equals("1") || gxyGroup.get(object[0].toString()).get("signType").toString().equals("2")) &&
                                    gxyGroup.get(object[0].toString()).get("signType").toString().equals(signType.toString())) {
                                continue;
                            }
                            gxyGroup.get(object[0].toString()).put("signType", 3);
                            continue;
                        }
                    } else if (group.equals("2")) {
                        if (tnbGroup.containsKey(object[0].toString())) {
                            if ((tnbGroup.get(object[0].toString()).get("signType").toString().equals("1") || tnbGroup.get(object[0].toString()).get("signType").toString().equals("2")) &&
                                    tnbGroup.get(object[0].toString()).get("signType").toString().equals(signType.toString())) {
                                continue;
                            }
                            tnbGroup.get(object[0].toString()).put("signType", 3);
                            continue;
                        }
                    } else {
                        if (tnbGroup.containsKey(object[0].toString())) {
                            if ((tnbGroup.get(object[0].toString()).get("signType").toString().equals("1") || tnbGroup.get(object[0].toString()).get("signType").toString().equals("2")) &&
                                    tnbGroup.get(object[0].toString()).get("signType").toString().equals(signType.toString())) {
                                continue;
                            }
                            tnbGroup.get(object[0].toString()).put("signType", 3);
                            continue;
                        }
                        if (gxyGroup.containsKey(object[0].toString())) {
                            if ((gxyGroup.get(object[0].toString()).get("signType").toString().equals("1") || gxyGroup.get(object[0].toString()).get("signType").toString().equals("2")) &&
                                    gxyGroup.get(object[0].toString()).get("signType").toString().equals(signType.toString())) {
                                continue;
                            }
                            gxyGroup.get(object[0].toString()).put("signType", 3);
                            continue;
                        }
                    }

                    JSONObject patientJson = new JSONObject();
                    // 设置患者标识
                    patientJson.put("code", code);
                    // 设置患者姓名
                    patientJson.put("name", name);
                    // 设置患者头像
                    patientJson.put("photo", photo);
                    // 设置患者年龄
                    patientJson.put("age", DateUtil.getAgeByBirthday(birthday));
                    // 设置患者性别
                    patientJson.put("sex", sex);
                    // 设置患者病情
                    patientJson.put("diseaseLevel", diseaseCondition);
                    // 设置患者病种
                    patientJson.put("disease", disease);
                    // 设置病历记录总数
                    patientJson.put("recordAmount", recordAmount);
                    // 设置签约日期
                    patientJson.put("qyrq", DateUtil.dateToStr(qyrq, DateUtil.YYYY_MM_DD));
                    // 设置签约类型
                    patientJson.put("signType", signType);
                    patientJson.put("idcard", idcard);

                    if(!StringUtils.isEmpty(diseases)){
                        patientJson.put("diseases",new JSONArray(diseases));
                    }else{
                        patientJson.put("diseases","");
                    }

                    if (group.equals("0")) {
                        ptGroup.put(code.toString(), patientJson);
                    } else if (group.equals("1")) {
                        gxyGroup.put(code.toString(), patientJson);
                    } else if (group.equals("2")) {
                        tnbGroup.put(code.toString(), patientJson);
                    } else {
                        gxyGroup.put(code.toString(), patientJson);
                        tnbGroup.put(code.toString(), patientJson);
                    }
                }

                // 设置患者数
                ptGroupJson.put("total", ptGroup.size());
                // 设置患者列表
                ptGroupJson.put("patients", new JSONArray(ptGroup.values()));
                // 设置患者数
                gxyGroupJson.put("total", gxyGroup.size());
                // 设置患者列表
                gxyGroupJson.put("patients", new JSONArray(gxyGroup.values()));
                // 设置患者数
                tnbGroupJson.put("total", tnbGroup.size());
                // 设置患者列表
                tnbGroupJson.put("patients", new JSONArray(tnbGroup.values()));
            }

            array.put(ptGroupJson);
            array.put(gxyGroupJson);
            array.put(tnbGroupJson);
            System.out.println("patients_disease_end:" + new Date());
            return write(200, "患者疾病分组列表查询成功！", "data", array);
        } catch (Exception e) {
            e.printStackTrace();
            return error(-1, "查询失败!");
        }
    }

    /**
     * 查询医生患者分组统计
     *
     * @return
     */
    @RequestMapping(value = "/patientcount")
    @ResponseBody
    public String groupPatientsCount() {
        try {
            JSONArray array = new JSONArray();

            array.put(doctorPatientGroupService.countDiseasePatient(getUID()));
            array.put(doctorPatientGroupService.countNormalPatient(getUID()));
            array.put(doctorPatientGroupService.countOldPatient(getUID()));

            return write(200, "患者分组统计查询成功！", "data", array);
        } catch (Exception e) {
            error(e);
            return invalidUserException(e, -1, "患者分组统计失败！");
        }
    }


    /**
     * 我的患者查询接口--根据患者姓名查询分组信息
     *
     * @param patientName 患者姓名
     * @return
     */
    @RequestMapping(value = "patientsByName")
    @ResponseBody
    public String patientsByName(String patientName) {
        try {
            System.out.println("patients_by_name_start:" + new Date());
            // 获取分组
            Iterable<DoctorPatientGroup> grouplists = doctorInfoService.findDoctorPatientGroup(getUID());
            // 获取医生下的患者
            List<Object> doctorPatients = doctorInfoService.findPatientByDoctorSign(getUID());
            JSONArray array = new JSONArray();
            if (doctorPatients != null) {
                for (DoctorPatientGroup grouplist : grouplists) {
                    if (grouplist == null) {
                        continue;
                    }
                    JSONObject groupJson = new JSONObject();
                    Map<String, JSONObject> patientsMap = new HashMap<>();

                    for (Object temp : doctorPatients) {
                        Object[] object = (Object[]) temp;
                        if (object == null || object.length != DOCTOR_PATIENT_OBJECT_LENGTH) {
                            continue;
                        }

                        // 分组标识
                        String group = (String) object[0];
                        // 患者标识
                        Object code = object[1];
                        // 姓名
                        String name = (String) object[2];

                        if (StringUtils.isNotBlank(name) && StringUtils.isNotBlank(patientName) && !name.contains(patientName)) {
                            continue;
                        }

                        // 头像
                        Object photo = object[3];
                        // 生日
                        Date birthday = (Date) object[4];
                        // 性别
                        Object sex = object[5];
                        // 病情：0绿标，1黄标，2红标
                        Object diseaseCondition = object[6];
                        // 疾病类型，0健康，1高血压，2糖尿病，3高血压+糖尿病
                        Object disease = object[7];
                        // 病历数
                        Object recordAmount = object[8];
                        // 随手记数
                        Object partAmount = object[9];
                        // 签约日期
                        Date qyrq = (Date) object[10];
                        // 签约类型（1表示三师签约，2表示家庭签约）
                        Object signType = object[11];
                        Object idcard = object[12];
                        if (StringUtils.equals(group, grouplist.getCode())) {
                            if (patientsMap.containsKey(object[1].toString())) {
                                if ((patientsMap.get(object[1].toString()).get("signType").toString().equals("1") || patientsMap.get(object[1].toString()).get("signType").toString().equals("2")) &&
                                        patientsMap.get(object[1].toString()).get("signType").toString().equals(signType.toString())) {
                                    continue;
                                }
                                patientsMap.get(object[1].toString()).put("signType", 3);
                                continue;
                            }
                            JSONObject patientJson = new JSONObject();
                            // 设置患者标识
                            patientJson.put("code", code);
                            // 设置患者姓名
                            patientJson.put("name", name);
                            // 设置患者头像
                            patientJson.put("photo", photo);
                            // 设置患者年龄
                            patientJson.put("age", DateUtil.getAgeByBirthday(birthday));
                            // 设置患者性别
                            patientJson.put("sex", sex);
                            // 设置患者病情
                            patientJson.put("diseaseLevel", diseaseCondition);
                            // 设置患者病种
                            patientJson.put("disease", disease);
                            // 设置病历记录总数
                            patientJson.put("recordAmount", recordAmount);
                            // 设置病历片段总数
                            patientJson.put("partAmount", partAmount);
                            // 设置签约日期
                            patientJson.put("qyrq", DateUtil.dateToStr(qyrq, DateUtil.YYYY_MM_DD));
                            // 设置签约类型
                            patientJson.put("signType", signType);
                            // 设置签约类型
                            patientJson.put("idcard", idcard);

                            String diseases = redisTemplate.opsForValue().get("disease:" + code.toString());
                            if(!StringUtils.isEmpty(diseases)){
                                patientJson.put("diseases",new JSONArray(diseases));
                            }else{
                                patientJson.put("diseases","");
                            }

                            patientsMap.put(code.toString(), patientJson);
                            //groupPatientArray.put(patientJson);
                        }
                    }
                    JSONArray groupPatientArray = new JSONArray(patientsMap.values());
                    // 设置分组标识
                    groupJson.put("code", grouplist.getCode());
                    // 设置分组名称
                    groupJson.put("name", grouplist.getName());
                    // 设置患者数
                    groupJson.put("total", groupPatientArray.length());
                    // 设置患者列表
                    groupJson.put("patients", groupPatientArray);
                    array.put(groupJson);
                }
            }
            System.out.println("patients_by_name_end:" + new Date());
            return write(200, "患者列表查询成功！", "data", array);
        } catch (Exception e) {
            error(e);
            return invalidUserException(e, -1, "患者列表查询失败！");
        }
    }

    /**
     * 患者信息查询接口
     *
     * @param code 患者标识
     * @param jyStatus 是否获取解约数据
     * @return
     */
    @RequestMapping(value = "patient")
    @ResponseBody
    public String patient(String code, String jyStatus) {
        try {
            Patient temp = patientInfoService.findByCode(code);
            if (temp != null) {
                JSONObject json = new JSONObject();
                // 设置患者标识
                json.put("code", temp.getCode());
                // 设置患者姓名
                json.put("name", temp.getName());
                // 设置患者头像
                json.put("photo", CommonUtil.getPhoneUrl(temp.getPhoto()));
                // 设置患者年龄
                json.put("age", DateUtil.getAgeByBirthday(temp.getBirthday()));
                // 设置患者性别
                json.put("sex", temp.getSex());
                // 设置患者病情：0绿标，1黄标，2红标
                json.put("diseaseLevel", temp.getDiseaseCondition());
                // 疾病类型名称，0健康，1高血压，2糖尿病，3高血压+糖尿病
                json.put("diseaseName", getDiseaseName(temp.getDisease()));
                // 疾病类型，0健康，1高血压，2糖尿病，3高血压+糖尿病
                json.put("disease", temp.getDisease());
                // 设置患者身份证号
                json.put("idCard", temp.getIdcard());
                // 设置患者出生年月
                json.put("birthday", DateUtil.dateToStr(temp.getBirthday(), DateUtil.YYYY_MM_DD));
                // 设置患者手机号码
                json.put("mobile", temp.getMobile());
                // 设置患者联系电话
                json.put("phone", temp.getPhone());
                // 设置患者居住省份
                json.put("provinceName", temp.getProvinceName());
                json.put("cityName", temp.getCityName());
                json.put("townName", temp.getTownName());
                json.put("streetName", temp.getStreetName());
                // 设置患者地址
                json.put("address", temp.getAddress());
                //设置患者医保号
                json.put("ssc", temp.getSsc());

                String diseases = redisTemplate.opsForValue().get("disease:" + code.toString());
                if(!StringUtils.isEmpty(diseases)){
                    json.put("diseases",new JSONArray(diseases));
                }else{
                    json.put("diseases","");
                }

                SignFamily jtSign = null;
                if( "1".equals(jyStatus)){
                    List<SignFamily> ls = signFamilyDao.findLastJySignByPatient(code, 2);
                    jtSign = ls.size()>0? ls.get(0) : null;
                }
                else
                    jtSign = signFamilyDao.findSignByPatient(code,2);
                SignFamily ssSign = signFamilyDao.findSignByPatient(code,1);


                // 家庭签约
                if(jtSign != null){
                    JSONObject jtJson = new JSONObject();
                    jtJson.put("code",jtSign.getCode());
                    jtJson.put("applyDate",DateUtil.dateToStr(jtSign.getPatientApplyDate(), DateUtil.YYYY_MM_DD_HH_MM_SS));
                    jtJson.put("applyUnsignDate",DateUtil.dateToStr(jtSign.getPatientApplyUnsignDate(), DateUtil.YYYY_MM_DD_HH_MM_SS));
                    jtJson.put("beginDate",DateUtil.dateToStr(jtSign.getBegin(), DateUtil.YYYY_MM_DD));
                    jtJson.put("endDate",DateUtil.dateToStr(jtSign.getEnd(), DateUtil.YYYY_MM_DD));
                    jtJson.put("expensesType",jtSign.getExpensesType());
                    jtJson.put("jyDate", DateUtil.dateToStr(jtSign.getApplyUnsignDate(), DateUtil.YYYY_MM_DD));
                    jtJson.put("status",jtSign.getStatus());
                    json.put("jtSign",jtJson);
                }else{
                    json.put("jtSign","");
                }
                // 三师签约
                if(ssSign != null){
                    JSONObject jtJson = new JSONObject();
                    jtJson.put("code",ssSign.getCode());
                    jtJson.put("beginDate",DateUtil.dateToStr(ssSign.getBegin(), DateUtil.YYYY_MM_DD));
                    jtJson.put("endDate",DateUtil.dateToStr(ssSign.getEnd(), DateUtil.YYYY_MM_DD));
                    json.put("ssSign",jtJson);
                }else{
                    json.put("ssSign","");
                }

                return write(200, "患者信息查询成功！", "data", json);
            } else {
                return error(-1, "患者信息查询失败！");
            }
        } catch (Exception e) {
            error(e);
            return invalidUserException(e, -1, "患者信息查询失败！");
        }
    }

    /**
     * 患者分组查询接口
     *
     * @return
     */
    @RequestMapping(value = "groups")
    @ResponseBody
    public String groups() {
        try {
            List<DoctorPatientGroup> groups = doctorPatientGroupService.groups(getUID());
            JSONArray array = new JSONArray();
            if (groups != null) {
                for (DoctorPatientGroup group : groups) {
                    if (group == null) {
                        continue;
                    }
                    JSONObject json = new JSONObject();
                    // 设置分组标识
                    json.put("code", group.getCode());
                    // 设置分组名称
                    json.put("name", group.getName());
                    // 是否为系统分组
                    json.put("isSys", StringUtils.isEmpty(group.getDoctor()));
                    array.put(json);
                }
            }
            return write(200, "查询成功！", "list", array);
        } catch (Exception e) {
            error(e);
            return error(-1, "查询失败！");
        }
    }

    /**
     * 新建分组
     *
     * @param name
     * @return
     */
    @RequestMapping(value = "add_group")
    @ResponseBody
    public String addGroup(String name) {
        try {
            if (doctorPatientGroupService.addGroup(getUID(), name) != null) {
                return success("新建分组成功！");
            } else {
                return error(-1, "新建分组失败！");
            }
        } catch (Exception e) {
            error(e);
            return error(-1, "新建分组失败！");
        }
    }

    /**
     * 删除组名
     *
     * @param group 分组标识
     * @return
     */
    @RequestMapping(value = "del_group")
    @ResponseBody
    public String deleteGroup(String group) {
        try {
            if (StringUtils.equals(group, "1") || StringUtils.equals(group, "2") || StringUtils.equals(group, "3")) {
                return error(-1, "该分组禁止操作！");
            }
            DoctorPatientGroup temp = doctorPatientGroupService.findGroupByCode(group);
            if (temp == null) {
                return error(-1, "分组信息不存在或已删除！");
            }
            if (StringUtils.isEmpty(temp.getDoctor())) {
                return error(-1, "不允许删除系统分组！");
            }
            if (!StringUtils.equals(temp.getDoctor(), getUID())) {
                return error(-1, "只允许删除自己的分组！");
            }
            doctorPatientGroupService.deleteGroup(group);
            return success("删除成功！");
        } catch (Exception e) {
            error(e);
            return error(-1, "删除失败！");
        }
    }

    /**
     * 修改组名
     *
     * @param group
     * @param name
     * @return
     */
    @RequestMapping(value = "modify_group")
    @ResponseBody
    public String modifyGroup(String group, String name) {
        try {
            if (StringUtils.equals(group, "1") || StringUtils.equals(group, "2") || StringUtils.equals(group, "3")) {
                return error(-1, "该分组禁止操作！");
            }
            if (StringUtils.isEmpty(name)) {
                return error(-1, "组名不允许为空！");
            }
            DoctorPatientGroup temp = doctorPatientGroupService.findGroupByCode(group);
            if (temp == null) {
                return error(-1, "分组信息不存在或已删除！");
            }
            if (StringUtils.isEmpty(temp.getDoctor())) {
                return error(-1, "不允许修改系统分组名称！");
            }
            if (!StringUtils.equals(temp.getDoctor(), getUID())) {
                return error(-1, "只允许修改自己的分组！");
            }
            temp.setName(name);
            doctorPatientGroupService.modifyGroup(temp);
            return success("组名修改成功！");
        } catch (Exception e) {
            error(e);
            return error(-1, "组名修改失败！");
        }
    }

    /**
     * 查询其他分组及患者
     *
     * @param group 分组标识
     * @return
     */
    @RequestMapping(value = "other_patients")
    @ResponseBody
    public String otherPatients(String group) {
        try {
            System.out.println("other_patient_start:" + new Date());
            // 获取分组
            Iterable<DoctorPatientGroup> grouplists = doctorInfoService.findDoctorPatientGroup(getUID());
            // 获取医生下的患者
            List<Object> doctorPatients = doctorInfoService.findPatientByDoctorSign(getUID());
            JSONArray array = new JSONArray();
            if (doctorPatients != null) {
                for (DoctorPatientGroup grouplist : grouplists) {
                    if (grouplist == null || StringUtils.equals(grouplist.getCode(), group)) {
                        continue;
                    }
                    JSONObject groupJson = new JSONObject();
                    Map<String, JSONObject> patientsMap = new HashMap<>();

                    for (Object temp : doctorPatients) {
                        Object[] object = (Object[]) temp;
                        if (object == null || object.length != DOCTOR_PATIENT_OBJECT_LENGTH) {
                            continue;
                        }
                        // 签约类型（1表示三师签约，2表示家庭签约）
                        Object signType = object[11];
                        // 分组标识
                        String groupCode = (String) object[0];
                        // 患者标识
                        Object code = object[1];
                        // 姓名
                        Object name = object[2];
                        // 头像
                        Object photo = object[3];
                        // 生日
                        Date birthday = (Date) object[4];
                        // 性别
                        Object sex = object[5];
                        // 病情：0绿标，1黄标，2红标
                        Object diseaseCondition = object[6];
                        // 疾病类型，0健康，1高血压，2糖尿病，3高血压+糖尿病
                        Object disease = object[7];
                        // 签约日期
                        Date qyrq = (Date) object[10];

                        Object idcard = object[12];

                        if (StringUtils.equals(groupCode, grouplist.getCode())) {
                            if (patientsMap.containsKey(object[1].toString())) {
                                if ((patientsMap.get(object[1].toString()).get("signType").toString().equals("1") || patientsMap.get(object[1].toString()).get("signType").toString().equals("2")) &&
                                        patientsMap.get(object[1].toString()).get("signType").toString().equals(signType.toString())) {
                                    continue;
                                }
                                patientsMap.get(object[1].toString()).put("signType", 3);
                                continue;
                            }
                            JSONObject patientJson = new JSONObject();
                            // 设置患者标识
                            patientJson.put("code", code);
                            // 设置患者姓名
                            patientJson.put("name", name);
                            // 设置患者头像
                            patientJson.put("photo", photo);
                            // 设置患者年龄
                            patientJson.put("age", DateUtil.getAgeByBirthday(birthday));
                            // 设置患者性别
                            patientJson.put("sex", sex);
                            // 设置患者病情
                            patientJson.put("diseaseLevel", diseaseCondition);
                            // 设置患者病种
                            patientJson.put("disease", disease);
                            // 设置签约日期
                            patientJson.put("qyrq", DateUtil.dateToStr(qyrq, DateUtil.YYYY_MM_DD));
                            // 设置签约类型
                            patientJson.put("signType", signType);
                            patientJson.put("idcard", idcard);

                            String diseases = redisTemplate.opsForValue().get("disease:" + code.toString());
                            if(!StringUtils.isEmpty(diseases)){
                                patientJson.put("diseases",new JSONArray(diseases));
                            }else{
                                patientJson.put("diseases","");
                            }

                            patientsMap.put(code.toString(), patientJson);
                        }
                    }

                    JSONArray groupPatientArray = new JSONArray(patientsMap.values());

                    // 设置分组标识
                    groupJson.put("code", grouplist.getCode());
                    // 设置分组名称
                    groupJson.put("name", grouplist.getName());
                    // 设置患者数
                    groupJson.put("total", groupPatientArray.length());
                    // 设置患者列表
                    groupJson.put("patients", groupPatientArray);
                    array.put(groupJson);
                }
            }
            System.out.println("other_patient_end:" + new Date());
            return write(200, "患者列表查询成功！", "data", array);
        } catch (Exception e) {
            error(e);
            return invalidUserException(e, -1, "患者列表查询失败！");
        }
    }

    /**
     * 添加患者到指定分组
     *
     * @param group
     * @param patients
     * @return
     */
    @RequestMapping(value = "add_patients")
    @ResponseBody
    public String addGroupPatients(String group, String patients) {
        try {
            if (StringUtils.equals(group, "1") || StringUtils.equals(group, "2") || StringUtils.equals(group, "3")) {
                return error(-1, "该分组禁止操作！");
            }
            if (StringUtils.isEmpty(patients)) {
                return error(-1, "请至少选择一位患者！");
            }
            List<DoctorPatientGroupInfo> list = new ArrayList<DoctorPatientGroupInfo>();
            String[] array = patients.split(",");
            for (String temp : array) {
                if (StringUtils.isEmpty(temp)) {
                    continue;
                }
                if (doctorPatientGroupService.isExistsInGroup(getUID(), group, temp) == 0) {
                    //查询签约信息
                    List<SignFamily> signFamilies = signFamilyDao.findByDoctorAndPatient(getUID(), temp);

                    if (signFamilies == null || signFamilies.size() < 1) {
                        return error(-1, "患者与医生没有签约!");
                    }
                    for (SignFamily signFamily : signFamilies) {
                        DoctorPatientGroupInfo dpgi = new DoctorPatientGroupInfo();
                        dpgi.setCzrq(new Date());
                        dpgi.setDoctor(getUID());
                        dpgi.setGroup(group);
                        dpgi.setPatient(temp);
                        dpgi.setPname(signFamily.getName());
                        dpgi.setSignType(String.valueOf(signFamily.getType()));
                        dpgi.setStatus(1);
                        list.add(dpgi);
                    }
                } else {
                    return error(-1, "居民已在该分组!");
                }
            }
            // 保存到数据库
            doctorPatientGroupService.addGroupPatients(list);
            return success("添加成功！");
        } catch (Exception e) {
            error(e);
            return error(-1, "添加失败！");
        }
    }

    /**
     * 带参数的我的患者查询接口
     * <p>
     * 根据组合条件，获取我的患者列表
     *
     * @param groups                分组ID，逗号分隔
     * @param signType              筛选条件：三师类型
     * @param diseaseCondition      筛选条件：疾病严重程度，逗号分隔
     * @param orderDiseaseCondition 排序条件：按病情严重程度排序
     * @return
     */
    @RequestMapping(value = "/patientsWithFilter")
    @ResponseBody
    public String getPatientsWithFilter(String patientName, String groups, String signType, String diseaseCondition, String orderDiseaseCondition) {
        try {
            System.out.println("patients_filter_start:" + new Date());
            // 获取分组
            Iterable<DoctorPatientGroup> grouplists = doctorInfoService.findDoctorPatientGroup(getUID());

            // 获取医生下的患者
            List<Map<String, Object>> doctorPatients = doctorPatientGroupService.getPatientsWithFilter(getUID(), patientName, groups, signType, diseaseCondition, orderDiseaseCondition);

            JSONArray array = new JSONArray();

            if (doctorPatients != null) {

                for (DoctorPatientGroup grouplist : grouplists) {
                    if (grouplist == null) {
                        continue;
                    }
                    JSONObject groupJson = new JSONObject();
                    Map<String, JSONObject> patients = new HashMap<>();

                    for (Map<String, Object> obj : doctorPatients) {

                        if (StringUtils.equals((String) obj.get("group_code"), grouplist.getCode())) {

                            JSONObject jo = new JSONObject(obj);
                            // 分组标识
                            String groupCode = jo.has("group_code") ? jo.getString("group_code") : "";
                            // 患者标识
                            Object code = jo.has("code") ? jo.getString("code") : "";
                            // 姓名
                            Object name = jo.has("name") ? jo.getString("name") : "";
                            // 头像
                            Object photo = jo.has("photo") ? jo.getString("photo") : "";
                            // 生日
                            Date birthday = jo.has("birthday") ? DateUtil.strToDateShort(jo.getString("birthday")) : DateUtil.strToDateShort("9999-12-31");
                            // 性别
                            Object sex = jo.has("sex") ? (Object) jo.get("sex") : new Integer(1);
                            // 病情：0绿标，1黄标，2红标
                            Object dc = jo.has("disease_condition") ? (Object) jo.get("disease_condition") : new Integer(1);// diseaseCondition
                            // 疾病类型，0健康，1高血压，2糖尿病，3高血压+糖尿病
                            Object disease = jo.has("disease") ? (Object) jo.get("disease") : new Integer(1);
                            // 签约日期
                            String qyrq = jo.has("qyrq") ? jo.getString("qyrq") : "";
                            // 签约类型（1表示三师签约，2表示家庭签约）
                            Object st = jo.has("sign_type") ? jo.getString("sign_type") : new Integer(1); // signType
                            Object idcard = jo.has("idcard") ? jo.getString("idcard") : ""; // signType

                            if (StringUtils.equals(groupCode, grouplist.getCode())) {
                                if (patients.containsKey(code)) {
                                    if ((patients.get(code.toString()).get("signType").toString().equals("1") || patients.get(code.toString()).get("signType").toString().equals("2")) &&
                                            patients.get(code.toString()).get("signType").toString().equals(String.valueOf(st))) {
                                        continue;
                                    }
                                    patients.get(code).put("signType", 3);
                                    continue;
                                }
                                JSONObject patientJson = new JSONObject();

                                // 设置分组标识
                                // patientJson.put("groupCode", groupCode);
                                // 设置患者标识
                                patientJson.put("code", code);
                                // 设置患者姓名
                                patientJson.put("name", name);
                                // 设置患者头像
                                patientJson.put("photo", photo);
                                // 设置生日
                                patientJson.put("birthday", DateFormat.getDateInstance(DateFormat.DEFAULT).format(birthday));
                                // 设置患者年龄
                                patientJson.put("age", jo.has("birthday") ? DateUtil.getAgeByBirthday(birthday) : "-");
                                // 设置患者性别
                                patientJson.put("sex", sex);
                                // 设置患者病情
                                patientJson.put("diseaseLevel", dc);
                                // 设置患者病种
                                patientJson.put("disease", disease);
                                // 设置签约日期
                                patientJson.put("qyrq", qyrq);
                                // 设置签约类型
                                patientJson.put("signType", st);
                                patientJson.put("idcard", idcard);

                                String diseases = redisTemplate.opsForValue().get("disease:" + code.toString());
                                if(!StringUtils.isEmpty(diseases)){
                                    patientJson.put("diseases",new JSONArray(diseases));
                                }else{
                                    patientJson.put("diseases","");
                                }
                                patients.put(code.toString(), patientJson);
                            }
                        }
                    }

                    // 设置分组标识
                    groupJson.put("code", grouplist.getCode());
                    // 设置分组名称
                    groupJson.put("name", grouplist.getName());
                    // 设置患者数
                    groupJson.put("total", patients.size());
                    // 设置患者列表
                    groupJson.put("patients", patients.values());
                    array.put(groupJson);

                }

            }
            System.out.println("patients_filter_end:" + new Date());
            return write(200, "患者列表查询成功!", "data", array);
        } catch (Exception e) {
            error(e);
            return invalidUserException(e, -1, "患者列表查询失败！");
        }
    }

    /**
     * 根据patient表的disease字段转换成相应的疾病类型 疾病类型，0健康，1高血压，2糖尿病，3高血压+糖尿病
     *
     * @return string
     */
    private String getDiseaseName(Integer disease) {
        if (disease != null) {
            switch (disease) {

                case 0:
                    return "健康";
                case 1:
                    return "高血压";
                case 2:
                    return "糖尿病";
                case 3:
                    return "高血压+糖尿病";

                default:
                    return "";
            }
        } else {
            return "";
        }
    }

    /**
     * 查询指定患者的家庭医生或三师医生列表
     *
     * @return
     */
    @RequestMapping(value = "sign_doctors")
    @ResponseBody
    public String signDoctors(String patient) {
        try {
            JSONObject data = new JSONObject();
            JSONArray array = new JSONArray();
            List<Doctor> doctors = new ArrayList<>();

            SignFamily signFamily = signFamilyDao.findByFamilyDoctorAndPatient(getUID(), patient);
            if (signFamily != null) {
                // 查询家庭医生团队
                doctors = drHealthTeamService.findTeamDoctors(signFamily.getTeamCode());
            }
            if (doctors != null && doctors.size() > 0) {
                for (Doctor doctor : doctors) {
                    if (doctor == null) {
                        continue;
                    }
                    JSONObject json = new JSONObject();
                    json.put("code", doctor.getCode());
                    json.put("name", doctor.getName());
                    json.put("photo", CommonUtil.getPhoneUrl(doctor.getPhoto()));
                    json.put("hospitalName", doctor.getHosptialName());
                    json.put("deptName", doctor.getDeptName());
                    json.put("jobName", doctor.getJobName());
                    json.put("expertise", doctor.getExpertise());
                    int type = doctor.getLevel();
                    if (type == 1) {
                        json.put("typename", "专科医生");
                    } else if (type == 2) {
                        json.put("typename", "全科医生");
                    } else if (type == 3) {
                        json.put("typename", "健康管理师");
                    } else {
                        json.put("typename", "");
                    }
                    array.put(json);
                }
                data.put("team", "");
            } else {
                SignFamily sanshiSign = signFamilyDao.findBySanshiDoctorAndPatient(getUID(), patient);
                if (sanshiSign != null) {
                    // 查询三师团队医生
                    doctors = drHealthTeamService.findTeamDoctors(patient, 1);
                } else {
                    doctors = new ArrayList<>();
                }

                for (Doctor doctor : doctors) {
                    if (doctor == null) {
                        continue;
                    }
                    JSONObject json = new JSONObject();
                    json.put("code", doctor.getCode());
                    json.put("name", doctor.getName());
                    json.put("photo", CommonUtil.getPhoneUrl(doctor.getPhoto()));
                    json.put("hospitalName", doctor.getHosptialName());
                    json.put("deptName", doctor.getDeptName());
                    json.put("jobName", doctor.getJobName());
                    json.put("expertise", doctor.getExpertise());
                    int type = doctor.getLevel();
                    if (type == 1) {
                        json.put("typename", "专科医生");
                    } else if (type == 2) {
                        json.put("typename", "全科医生");
                    } else if (type == 3) {
                        json.put("typename", "健康管理师");
                    } else {
                        json.put("typename", "");
                    }
                    array.put(json);
                }
                data.put("team", "");
            }
            data.put("list", array);
            return write(200, "获取签约医生成功！", "data", data);
        } catch (Exception e) {
            error(e);
            return invalidUserException(e, -1, "获取签约医生失败！");
        }
    }


    /**
     * 校验患者手机号是否呗注册
     * @return
     */
    @RequestMapping(value = "checkMobile")
    @ResponseBody
    public String checkMobile(String mobile) {
        try {
            patientInfoService.checkMobile(mobile);
            return write(200, "验证成功");
        } catch (Exception e) {
            error(e);
            return error(-1, "验证异常！");
        }
    }
}
